using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using MyCompany.WebCrawler.Tasks;

namespace MyCompany.WebCrawler.Repositories
{
    public class TaskQueue
    {        
        private readonly object locker = "Locker";
        Queue<ITask> tasks = new Queue<ITask>();

        public void Enqueue(ITask task)
        {
            lock (locker)
            {
                Trace.WriteLine(" + " + task);

                tasks.Enqueue(task);
                Monitor.Pulse(locker);
            }
        }

        public ITask Denqueue()
        {
            lock (locker)
            {
                Trace.WriteLine(" Tasks: " + Count);
                if (Count == 0)
                    Monitor.Wait(locker);

                var task = tasks.Dequeue();

                Trace.WriteLine(" - " + task);
                return task;
            }
        }

        public int Count
        {
            get { return tasks.Count; }
        }

        internal IEnumerable<ITask> ToList()
        {
            return tasks.ToList();
        }
    }
}